import './MForm.scss';
import * as React from 'react';
import { Form } from 'antd';
import { FormComponentProps } from 'antd/lib/form/Form';
import LoadingComponent, { ILoadingProps } from '../common/LoadingComponent';


export interface IFormProps extends FormComponentProps, ILoadingProps {
  show?: boolean;
  onChange?: Function;
  data?: any;
  onSubmit?: Function;
  onClose?: Function;
}

export const createMForm = function (component) {
  return Form.create({
    withRef: true,
    onFieldsChange(props, changedFields) {
      if (props.onChange) {
        props.onChange(changedFields);
      }
    },
    mapPropsToFields(props) {
      if (props) {
        let map = {};
        for (let field in props) {
          if (props.hasOwnProperty(field)) {
            map[field] = {
              'value': props[field]
            };
          }
        }
        return map;
      }
    },
  })(component);
};

export const FormItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 14 },
};


class MForm extends LoadingComponent<IFormProps, any>{
  constructor(props: any) {
    super(props);
  }

  componentWillMount() {
    super.componentWillMount();
    window.addEventListener('keydown', this.handleKeyDown);
  }

  componentWillUnmount() {
    super.componentWillUnmount();
    window.removeEventListener('keydown', this.handleKeyDown);
  }

  handleKeyDown = (e) => {
    if (e.keyCode === 13 && this.props.onSubmit) {
      this.props.onSubmit();
    }
  }


  // override for Compile not error
  getChildContext() {
    // override for Compile not error
  };

  // override for Compile not error
  validateFields(callback?: Function) {
    console.log('myFormValidate......................');
    this.props.form.validateFields((errors, fields) => {
      if (callback) {
        callback(errors, fields);
      }
    });
  }
}
export default MForm;
